﻿using 软件运行平台.ViewModel;
using MaterialDesignThemes.Wpf;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Data;
using System.Windows.Documents;
using System.Windows.Input;
using System.Windows.Media;
using System.Windows.Media.Imaging;
using System.Windows.Navigation;
using System.Windows.Shapes;
using 软件运行平台.View;
using System.IO;
using Forms = System.Windows.Forms;
using System.Diagnostics;
using System.Windows.Controls.Primitives;
using System.Runtime.InteropServices;
using MengXunAppTool.Helper;
using MengXunAppTool.DAL;
using ICSharpCode.SharpZipLib.Zip;
using System.Threading;

namespace 软件运行平台
{
    /// <summary>
    /// Interaction logic for MainWindow.xaml
    /// </summary>
    public partial class MainWindow : Window
    {
        private VerDAL verDAL = new VerDAL();
        private ConfigHelper configHelper = new ConfigHelper();
        WindowState ws;
        WindowState wsl;
        System.Windows.Forms.NotifyIcon notifyIcon;
        public bool IsQE = false;
        public static MesTool.Model.UserModel userModel = null;
        public MainWindow()
        {
            try
            {
                //string err = "";
                //MesTool.UserBLL.SendMsg( "hello",ref err,"101289");
                string customer = "盟讯";
                string product = "通用";
                string softwarename = "软件运行平台";
                string lastVer = verDAL.GetLastVer(customer, product, softwarename);
                Dictionary<string, string> dic = configHelper.ReadAll(System.Environment.CurrentDirectory + "\\Update\\自动升级工具.exe.config");
                string localVer = dic["Version"];
                string filePath = AppDomain.CurrentDomain.BaseDirectory + "ConfigBackUp";
                if (!Directory.Exists(filePath))
                {
                    Directory.CreateDirectory(filePath);
                }
                string config = AppDomain.CurrentDomain.BaseDirectory + "软件运行平台.exe.config";
                if (localVer != lastVer)
                {
                    File.Copy(config, filePath + "\\软件运行平台.exe.config",true);
                    Process process1 = new Process();
                    process1.StartInfo.WorkingDirectory = System.Environment.CurrentDirectory + "\\Update";
                    process1.StartInfo.FileName = "自动升级工具.exe";
                    process1.Start();
                    this.Close();
                    return;
                }
                if (File.Exists(filePath + "\\软件运行平台.exe.config"))
                {
                    File.Delete(config);
                    File.Copy(filePath + "\\软件运行平台.exe.config", config,true);
                    File.Delete(filePath + "\\软件运行平台.exe.config");
                }

                //if (File.Exists(System.Environment.CurrentDirectory + "\\软件运行平台" + localVer + ".zip"))
                //{
                //    FileInfo zipFile = new FileInfo(System.Environment.CurrentDirectory + "\\软件运行平台" + localVer + ".zip");
                //    FileInfo updateFile = new FileInfo(System.Environment.CurrentDirectory + "\\Update\\自动升级工具.exe.config");
                //    if (zipFile.LastWriteTime > updateFile.LastWriteTime)
                //    {
                //        while (IsFileInUse(zipFile.FullName))
                //        {
                //            Thread.Sleep(200);
                //        }
                //        Decompress(zipFile.FullName, zipFile.FullName.Substring(0, zipFile.FullName.LastIndexOf('\\')));
                //        configHelper.Write(System.Environment.CurrentDirectory + "\\Update\\自动升级工具.exe.config", "Version", localVer);
                //    }
                //}
                InitializeComponent();
                //string baseImg = Win32Helper.GetDesktopWallpaper();
                //System.Drawing.Bitmap bitmap = new System.Drawing.Bitmap(baseImg);
                //System.Windows.Media.ImageBrush ib = new System.Windows.Media.ImageBrush();
                //ib.Opacity = 0.1;
                //IntPtr ip = bitmap.GetHbitmap();
                //ib.ImageSource = System.Windows.Interop.Imaging.CreateBitmapSourceFromHBitmap(ip, IntPtr.Zero, Int32Rect.Empty, System.Windows.Media.Imaging.BitmapSizeOptions.FromEmptyOptions());
                //BaseGrid.Background = ib;


                Win32Helper.CreateDesktopShortcut("软件运行平台", System.Environment.CurrentDirectory + "\\软件运行平台.exe");
                Rect rect = Win32Helper.GetWindowsRect();
                if (rect.Width<1920)
                {
                    this.Width = rect.Width - 200;
                    this.Height = rect.Height - 200;
                }

                // icon();
                //保证窗体显示在上方。
                //wsl = WindowState;
                this.Title = "软件运行平台" + localVer;
            }
            catch (Exception ee)
            {
                HandyControl.Controls.Growl.Error(ee.Message.ToString());
               LogHelper.WriteLog(ee.ToString());
                this.Close();
            }
        }
        internal void SwitchScreen(object sender)
        {
            var screen = ((UserControl)sender);

            if (screen != null)
            {
                StackPanelMain.Children.Clear();
                StackPanelMain.Children.Add(screen);
            }
        }
        private void InitItem()
        {
            Menu.Children.Clear();
            StackPanelMain.Children.Clear();
            List<AppsViewModel> appModels = new List<AppsViewModel>();
            Dictionary<string, string> dic = configHelper.ReadAll();
            string localCus = dic["Customer"];
            string localPro = dic["Product"];
                try
                {
                    var apps = verDAL.GetAllApp(IsQE, userModel?.nickName);
                    foreach (var app in apps)
                    {
                        AppsViewModel appsModel = appModels.FirstOrDefault(it => it.Customer == app.Customer);
                        if (appsModel == null)
                        {
                            if (app.Customer != localCus && localCus != "")
                            {
                                continue;
                            }
                            appsModel = new AppsViewModel();
                            appsModel.Customer = app.Customer;
                            appModels.Add(appsModel);
                        }
                        AppsViewModel.Product prod = appsModel.Products.FirstOrDefault(it => it.Prod == app.Product);
                        if (prod == null)
                        {
                            if (app.Product != localPro && localPro != "")
                            {
                                continue;
                            }
                            prod = new AppsViewModel.Product();
                            prod.Prod = app.Product;
                            appsModel.Products.Add(prod);
                        }
                        if (prod.Softwares.Count(it => it.AppName == app.AppName) == 0)
                        {
                            var lastApp = apps.FirstOrDefault(it => it.Customer == app.Customer && it.Product == app.Product && it.AppName == app.AppName);
                            prod.Softwares.Add(lastApp);
                        }
                    }

                    foreach (AppsViewModel model in appModels)
                    {
                        var subItems = new List<MenuViewModel.SubItem>();
                        foreach (var item in model.Products)
                        {
                            subItems.Add(new MenuViewModel.SubItem(item.Prod, new AppsView(item.Softwares, this)));
                        }
                        PackIconKind icon = PackIconKind.AccountMultiple;
                        switch (model.Customer)
                        {
                            case var a when a.Contains("中移"): { icon = PackIconKind.Sim; }; break;
                            case var a when a.Contains("海康"): { icon = PackIconKind.Cctv; }; break;
                            case var a when a.Contains("英业达"): { icon = PackIconKind.Computer; }; break;
                            case var a when a.Contains("惠科"): { icon = PackIconKind.Tv; }; break;
                            case var a when a.Contains("万创"): { icon = PackIconKind.Tablet; }; break;
                            case var a when a.Contains("物奇"): { icon = PackIconKind.Gauge; }; break;
                            default:
                                break;
                        }
                        bool isSetStation = false;
                        if (localCus != "" && localPro != "")
                        {
                            isSetStation = true;
                        }
                        var menuItem = new MenuViewModel.MenuItem(model.Customer, subItems, icon, isSetStation);
                        var menuView = new MenuItemView(menuItem, this);
                        Menu.Children.Add(menuView);
                        if (isSetStation == true && subItems.Count > 0)
                        {
                            SwitchScreen(subItems[0].Screen);
                        }
                    }
                }
                catch (Exception ee)
                {
                    HandyControl.Controls.MessageBox.Error(ee.Message.ToString());
                    LogHelper.WriteLog(ee.ToString());
                    this.Close();
                }
        }

        private void icon()
        {
            //string logPath = System.IO.Path.GetFullPath(@"Picture\log.png");
            //this.Log.Source = Image.
            string icoPath = System.IO.Path.GetFullPath(@"bitbug_favicon.ico");
            if (File.Exists(icoPath))
            {
                this.notifyIcon = new System.Windows.Forms.NotifyIcon();
                this.notifyIcon.Text = "软件运行平台";//最小化到托盘时，鼠标点击时显示的文本
                System.Drawing.Icon icon = new System.Drawing.Icon(icoPath);//程序图标
                this.notifyIcon.Icon = icon;
                this.notifyIcon.Visible = true;
                notifyIcon.MouseDoubleClick += OnNotifyIconDoubleClick;
                notifyIcon.MouseDown += OnNotifyIconMouseClick;
            }

        }
        private void OnNotifyIconMouseClick(object sender, Forms.MouseEventArgs e)
        {
            if (e.Button == Forms.MouseButtons.Right)
            {
                Forms.ContextMenuStrip cms = new Forms.ContextMenuStrip();
                //关联 NotifyIcon 和 ContextMenuStrip
                notifyIcon.ContextMenuStrip = cms;
                System.Windows.Forms.ToolStripMenuItem showMenuItem = new System.Windows.Forms.ToolStripMenuItem();
                showMenuItem.Text = "显示";
                showMenuItem.Click += new EventHandler(showMenuItem_Click);
                System.Windows.Forms.ToolStripMenuItem hideMenumItem = new System.Windows.Forms.ToolStripMenuItem();
                hideMenumItem.Text = "隐藏";
                hideMenumItem.Click += new EventHandler(hideMenumItem_Click);
                System.Windows.Forms.ToolStripMenuItem exitMenuItem = new System.Windows.Forms.ToolStripMenuItem();
                exitMenuItem.Text = "退出";
                exitMenuItem.Click += new EventHandler(exitMenuItem_Click);

                cms.Items.Add(exitMenuItem);
                cms.Items.Add(hideMenumItem);
                cms.Items.Add(showMenuItem);
            }
        }
        private void exitMenuItem_Click(object sender, EventArgs e)
        {
            notifyIcon.Visible = false;
            System.Environment.Exit(0);
        }

        private void hideMenumItem_Click(object sender, EventArgs e)
        {
            this.WindowState = WindowState.Minimized;
        }

        private void showMenuItem_Click(object sender, EventArgs e)
        {
            this.Show();
            WindowState = wsl;
        }
        private void OnNotifyIconDoubleClick(object sender, EventArgs e)
        {
            this.Show();
            WindowState = wsl;
        }

        private void window_StateChanged(object sender, EventArgs e)
        {
            //ws = this.WindowState;
            if (this.WindowState == WindowState.Minimized)
            {
                //this.Hide();
                //InitItem();
            }
        }

        private void window_Closed(object sender, EventArgs e)
        {
            //this.notifyIcon.Visible = false;
            System.Environment.Exit(0);
        }

        private void box_PreviewMouseLeftButtonDown(object sender, MouseButtonEventArgs e)
        {
            try
            {
                //位置
                contextMenu.PlacementTarget = box;
                contextMenu.Placement = PlacementMode.Bottom;
                contextMenu.HorizontalOffset = -180;
                //显示菜单
                contextMenu.IsOpen = true;
            }
            catch (Exception ee)
            {
                HandyControl.Controls.Growl.Error(ee.Message.ToString());
               LogHelper.WriteLog(ee.ToString());
            }
        }

        private void TextBlockRefresh_MouseLeftButtonUp(object sender, MouseButtonEventArgs e)
        {
            this.Cursor = Cursors.Wait;
            InitItem();
            this.Cursor = Cursors.Arrow;
        }

        private void TextBlockSetStation_MouseLeftButtonUp(object sender, MouseButtonEventArgs e)
        {
            new View.StaionSetView().ShowDialog();
            this.Cursor = Cursors.Wait;
            InitItem();
            this.Cursor = Cursors.Arrow;
        }
        public static bool IsFileInUse(string fileName)
        {
            bool inUse = true;
            FileStream fs = null;
            try
            {
                fs = new FileStream(fileName, FileMode.Open, FileAccess.Read,
                FileShare.None);
                inUse = false;
            }
            catch
            {
            }
            finally
            {
                if (fs != null)
                    fs.Close();
            }
            return inUse;//true表示正在使用,false没有使用  
        }
        public void Decompress(string GzipFile, string targetPath)
        {
            string directoryName = targetPath;
            if (!Directory.Exists(directoryName)) Directory.CreateDirectory(directoryName);//生成解压目录    
            string CurrentDirectory = directoryName;
            byte[] data = new byte[2048];
            int size = 2048;
            ZipEntry theEntry = null;
            using (ZipInputStream s = new ZipInputStream(File.OpenRead(GzipFile)))
            {
                while ((theEntry = s.GetNextEntry()) != null)
                {
                    if (theEntry.IsDirectory)
                    {// 该结点是目录    
                        if (!Directory.Exists(CurrentDirectory + theEntry.Name)) Directory.CreateDirectory(CurrentDirectory + theEntry.Name);
                    }
                    else
                    {

                        if (theEntry.Name != String.Empty)
                        {
                            //  检查多级目录是否存在  
                            if (theEntry.Name.Contains("/"))
                            {
                                string parentDirPath = theEntry.Name.Remove(theEntry.Name.LastIndexOf("/") + 1);
                                if (!parentDirPath.Equals("Update/"))
                                {
                                    continue;
                                }
                                if (!Directory.Exists(CurrentDirectory + "\\" + parentDirPath))
                                {
                                    Directory.CreateDirectory(CurrentDirectory + "\\" + parentDirPath);
                                }
                                using (FileStream streamWriter = File.Create(CurrentDirectory + "\\" + theEntry.Name))
                                {
                                    while (true)
                                    {
                                        size = s.Read(data, 0, data.Length);
                                        if (size <= 0) break;
                                        streamWriter.Write(data, 0, size);
                                    }
                                    streamWriter.Close();
                                }
                            }  
                        }
                    }
                }
                s.Close();
            }
        }

        private void TextBlockLogIn_MouseLeftButtonUp(object sender, MouseButtonEventArgs e)
        {
            bool? dialog = new View.LogInView("http://192.168.2.23:9213/integrate/login/queryGenerLogin").ShowDialog();
            if (dialog == true)
            {
                IsQE = true;
                InitItem();
            }
        }

        private void window_Loaded(object sender, RoutedEventArgs e)
        {
            InitItem();
        }
    }
}